package by.yakusekmaxim.bookgid.webapp.page.home.author;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.inject.Inject;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.ResourceModel;

import by.yakusekmaxim.bookgid.dataaccess.util.Filter;
import by.yakusekmaxim.bookgid.datamodel.Author;
import by.yakusekmaxim.bookgid.datamodel.Book;
import by.yakusekmaxim.bookgid.datamodel.Book_;
import by.yakusekmaxim.bookgid.services.BookService;
import by.yakusekmaxim.bookgid.webapp.page.HomeLayout;
import by.yakusekmaxim.bookgid.webapp.page.home.book.BookPage;

public class AuthorDetailsPage extends HomeLayout {

	@Inject
	private BookService bookService;

	private Author author;

	protected void onInitialize() {
		super.onInitialize();

		Label imageLabel = new Label("imageLabel", "");
		if (author.getImage() != null) {
			imageLabel.add(AttributeModifier.replace("src", author.getImage()
					.getUrl()));
		}
		add(imageLabel);

		Label nameLabel = new Label("name", author.getName());
		add(nameLabel);

		Label nameOrLabel = new Label("nameOr", author.getNameOr());
		add(nameOrLabel);

		Label yearBirthLabel = new Label("YearBirth",
				getDataFormat(author.getYearBirth()));
		add(yearBirthLabel);

		Label yearDeathLabel = new Label("YearDeath",
				getDataFormat(author.getYearDeath()));
		add(yearDeathLabel);

		Label birthplaceLabel = new Label("Birthplace", author.getBirthplace());
		add(birthplaceLabel);

		Link<Object> bookLink = new Link<Object>("bookLink") {
			@Override
			public void onClick() {
				Filter<Book> filter = new Filter<Book>();
				filter.setEnabled(true);
				filter.setAttribute(Book_.author);
				filter.setValue(author);
				setResponsePage(new BookPage(filter, new ResourceModel(
						"p.admin.author.bookLink").getObject()
						+ author.getName()));
			}
		};

		bookLink.setEnabled(bookService.getCount(Book_.author, author) != 0);
		bookLink.add(new Label("bookCount", bookService.getCount(Book_.author,
				author)));
		add(bookLink);

		Label biographyLabel = (Label) new Label("Biography",
				author.getBiography()).setEscapeModelStrings(false);
		add(biographyLabel);

	}

	public AuthorDetailsPage(Author author) {
		this.author = author;
	}

	@Override
	protected MarkupContainer addPanel() {
		// TODO Auto-generated method stub
		return null;
	}

	private String getDataFormat(Date date) {
		if (date == null) {
			return "-";
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
		return dateFormat.format(date);
	}
}
